from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import orm, select, update

from model.user import AddressList
from schema.address import IAddressListPost, IAddressListPut


class CRUDAddress:
    async def get(self, address_id: int, db_session: AsyncSession):
        return await db_session.get(AddressList, address_id, options=[orm.selectinload(AddressList.type_address)])

    async def get_multi(self, offset: int, limit: int, db_session: AsyncSession):
        return ((await db_session.execute(select(AddressList)
                                          .options(orm.selectinload(AddressList.type_address))
                                          .limit(limit)
                                          .offset(offset)))
                .scalars())

    async def add(self, schema: IAddressListPost, db_session: AsyncSession):
        obj = AddressList(**schema.model_dump())
        db_session.add(obj)
        await db_session.commit()
        await db_session.refresh(obj)
        return obj

    async def modify(self, address_id: int, schema: IAddressListPut, db_session: AsyncSession):
        args = schema.model_dump()
        address_obj = await db_session.execute(update(AddressList).where(AddressList.id == address_id),
                                               args)
        await db_session.commit()
        return 'ok'


address = CRUDAddress()
